
#!/usr/bin/env python2.5
# -*- coding: UTF-8 -*-  
#
# This is an sample AppEngine application that shows how to 1) log in a user
# using the Twitter OAuth API and 2) extract their timeline.
#
# INSTRUCTIONS: 
#
# 1. Set up a new AppEngine application using this file, let's say on port 
# 8080. Rename this file to main.py, or alternatively modify your app.yaml 
# file.)
# 2. Fill in the application ("consumer") key and secret lines below.
# 3. Visit http://localhost:8080 and click the "login" link to be redirected
# to Twitter.com.
# 4. Once verified, you'll be redirected back to your app on localhost and
# you'll see some of your Twitter user info printed in the browser.
# 5. Copy and paste the token and secret info into this file, replacing the 
# default values for user_token and user_secret. You'll need the user's token 
# & secret info to interact with the Twitter API on their behalf from now on.
# 6. Finally, visit http://localhost:8080/timeline to see your twitter 
# timeline.
#


__author__ = "Mike Knapp"

import  OAuthClient as   oauth
import models
users = models.ApplUser
ApplService = models.ApplService
ApplUser=models.ApplUser
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import logging

 
from  milonpy import NMhtml as html
class HanlerTwitterOAuth(webapp.RequestHandler): 
    def get(self, mode=""): 
        #self.get_by_key_name(ck, rpc= db.create_rpc(read_policy=db.EVENTUAL_CONSISTENCY))
        UserLoged = users.get_current_user()
        UserAppl=ApplUser.all().filter('userID =', UserLoged.user_id()).fetch(1)
        if len(UserAppl)==0:
            logging.info('UserAppl:'+ repr(UserLoged) + ' not authorized for this Application yet') 
            if mode in ('login', 'verify', ""):
                applEntity=ApplService.get_by_key_name("twitter|geognos")
            else: 
                self.response.out.write(html.h1("operation not allowed for anauthorized user" )) 
                return
        else:
            logging.info('is Authorized for:'+ repr(UserLoged) ) 
            UserAppl=UserAppl[0] 
            applEntity=UserAppl.appkey 
        if applEntity is None:return self.response.out.write(html.h1("Cant find applEntity"))
        # Your application Twitter application ("consumer") key and secret.
        # You'll need to register an application on Twitter first to get this
        # information: http://www.twitter.com/oauth
        # application_key =VarDic['application_key']
        # application_secret =VarDic['application_secret']  
        
        # Fill in the next 2 lines after you have successfully logged in to 
        # Twitter per the instructions above. This is the *user's* token and 
        # secret. You need these values to call the API on their behalf after 
        # they have logged in to your app.
        #user_token =  VarDic['user_token']
        #user_secret = VarDic['user_secret']
        
        # In the real world, you'd want to edit this callback URL to point to your
        # production server. This is where the user is sent to after they have
        # authenticated with Twitter.  
        callback_url="%sverify" %(self.request.url.replace(mode, ""))
        #self.response.out.write(callback_url) 
        
        client = oauth.TwitterClient(applEntity,callback_url) 
        if mode == "login":  
            return self.redirect(client.get_authorization_url()) 
        if mode == "verify": 
            auth_token = self.request.get("oauth_token")
            auth_verifier = self.request.get("oauth_verifier") 
            user_info = client.get_user_info(auth_token, auth_verifier=auth_verifier)
            self.response.out.write(user_info)
            applUserEntity = ApplUser(appkey= applEntity,apSpcD=user_info, tokn=user_info['token'], secr=user_info['secret'],accTP= user_info['service'], userID=UserLoged.user_id())
            applUserEntity.put()
            return True
          
        if mode == "timeline":
            logging.info("geting timeline")  
            timeline_url = "http://twitter.com/statuses/user_timeline.xml"
            result = client.make_request(url=timeline_url, token=UserAppl.tokn,secret=UserAppl.secr)
            return self.response.out.write(result.content)
        login_url = "%s%slogin" % (self.request.host_url,self.request.path_info) 
        lnk=html.a("Login via Twitter", "",login_url )
        self.response.out.write(lnk())

class HadlerTwitter(webapp.RequestHandler): 
    def get(self,  mode=""):
        tmp=html.div("twitter Allication")
        self.response.out.write(tmp())

def main():
    application = webapp.WSGIApplication([('/oauth/twitter/(.*?)', HanlerTwitterOAuth), ('/appl/twitter/(.*?)', HadlerTwitter) ],
                                       debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
